package com.gjxjl.jdbc.gateway.handler;

import com.gjxjl.jdbc.gateway.config.ProxyConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class BackendConnector {
    private static final Logger logger = LogManager.getLogger(BackendConnector.class);
    private static final EventLoopGroup backendGroup = new NioEventLoopGroup();

    public static void connect(ProxyConfig config, Channel clientChannel, BackendConnectionListener listener) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(backendGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 后端连接的处理器：简单的转发
                        ch.pipeline().addLast(new BackendHandler(clientChannel));
                    }
                })
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);

        ChannelFuture future = bootstrap.connect(config.getBackendHost(), config.getBackendPort());

        future.addListener((ChannelFutureListener) f -> {
            if (f.isSuccess()) {
                logger.info("Connected to backend: {}:{}", config.getBackendHost(), config.getBackendPort());
                listener.onBackendConnected(f.channel());
            } else {
                logger.error("Failed to connect to backend", f.cause());
                listener.onBackendConnectFailed(f.cause());
            }
        });
    }

    public static void shutdown() {
        backendGroup.shutdownGracefully();
    }
}

interface BackendConnectionListener {
    void onBackendConnected(Channel backendChannel);
    void onBackendConnectFailed(Throwable cause);
}
